package com.open.capacity.workflow3.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.open.capacity.common.FileService;
import com.open.capacity.commons.CodeEnum;
import com.open.capacity.commons.PageResult;
import com.open.capacity.model.system.SysUser;
import com.open.capacity.reimburse.util.uuid.UUIDUtils;
import com.open.capacity.user.model.SysFile;
import com.open.capacity.user.service.SysFileService;
import com.open.capacity.utils.SysUserUtil;
import com.open.capacity.utils.file.FileUtils;
import com.open.capacity.workflow3.dao.BaseStampDao;
import com.open.capacity.workflow3.dao.NwfConfluenceDao;
import com.open.capacity.workflow3.entity.BaseStamp;
import com.open.capacity.workflow3.entity.NwfConfluence;
import com.open.capacity.workflow3.entity.NwfSchemeinfo;
import com.open.capacity.workflow3.service.BaseStampService;
import com.open.capacity.workflow3.service.NwfConfluenceService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.MapUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Slf4j
@Service
public class BaseStampServiceImpl implements BaseStampService {

    @Autowired
    private BaseStampDao stampDao;

    @Autowired
    private SysFileService fileService;

    @Autowired
    private FileService fileService2;

    @Value("${file.uploadpath:/usr/local/files/upload}")
    private String fileuploadPath;


    @Override
    public List<BaseStamp> getList(String keyword) {
        Map<String, Object> param = new HashMap<>();
        param.put("status", 1);
        param.put("keyword", keyword);
        return stampDao.findAll(param);
    }

    @Override
    public PageResult<BaseStamp> getPageList(Map<String, Object> params) {
        //设置分页信息，分别是当前页数和每页显示的总记录数【记住：必须在mapper接口中的方法执行之前设置该分页信息】
        if (MapUtils.getInteger(params, "page") != null && MapUtils.getInteger(params, "limit") != null) PageHelper.startPage(MapUtils.getInteger(params, "page"), MapUtils.getInteger(params, "limit"), true);

        List<BaseStamp> list = stampDao.findAll(params);
        PageInfo<BaseStamp> pageInfo = new PageInfo(list);

        return PageResult.<BaseStamp>builder().data(pageInfo.getList()).resp_code(CodeEnum.SUCCESS.getCode()).count(pageInfo.getTotal()).build();

    }

    @Override
    public BaseStamp getEntity(String keyValue) {
        return stampDao.findById(keyValue);
    }

    @Override
    public void save(String keyValue, BaseStamp stampEntity) {
        SysUser current = SysUserUtil.getLoginAppUser();
        stampEntity.setUpdateTime(new Date());
        stampEntity.setUpdateUserid(current.getId());
        stampEntity.setUpdateUsername(current.getRealName());
        if (StringUtils.isEmpty(keyValue)) {
            stampEntity.setId(UUIDUtils.getOriginalUUIDWithoutBar());
            stampDao.save(stampEntity);
        } else {
            stampEntity.setId(keyValue);
            stampDao.update(stampEntity);
        }
    }

    @Override
    public void delete(String keyValue) {
        stampDao.delete(keyValue);
    }

    @Override
    public void updateState(String keyValue, int state) {
        BaseStamp stamp = stampDao.findById(keyValue);
        stamp.setStatus(state);
        stampDao.update(stamp);
    }

    @Override
    public void getImg(String keyValue, HttpServletResponse response, HttpServletRequest request) {
        BaseStamp entity = stampDao.findById(keyValue);
        String fileName = "";
        if (entity != null && StringUtils.isNotEmpty(entity.getFileId())) {
            SysFile imgEntity = fileService.findById(entity.getFileId());
            if (imgEntity != null && StringUtils.isNotEmpty(imgEntity.getContext())) {
//                FileDownHelper.DownLoadBase64(imgEntity.F_Content, imgEntity.F_Name); //TODO 下载base64
                return;
            } else {
                fileName = imgEntity.getUrl();
            }
        } else {
            fileName = "/content/images/add.jpg";
        }
        if (StringUtils.isEmpty(fileName)) {
            fileName = "/content/images/add.jpg";
        }

        try {
//            if (!FileUtils.isValidFilename(fileName)) {
//                throw new Exception(StringUtils.format("文件名称({})非法，不允许下载。 ", fileName));
//            }
            String realFileName = fileName.substring(fileName.lastIndexOf("/") + 1);
            String filePath = fileuploadPath + fileName;

            response.setCharacterEncoding("utf-8");
            response.setContentType("multipart/form-data");
            response.setHeader("Content-Disposition",
                    "attachment;fileName=" + FileUtils.setFileDownloadHeader(request, realFileName));
            FileUtils.writeBytes(filePath, response.getOutputStream());

        } catch (Exception e) {
            log.error("下载文件失败", e);
        }
    }

    @Override
    public Boolean equalPassword(String keyValue, String password) {
        if (stampDao.findById(keyValue).getUsePassword().equals(password)) {
            return true;
        }
        return false;
    }
}
